package com.basic.bio.chat.singlechat;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Description:
 * @Date: 2024-03-29 10:30
 * @Author: wz
 **/
public class Client {

    public static void main(String[] args) {
        try {
            Socket socket = new Socket("127.0.0.1", 8888);
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            PrintStream writer = new PrintStream(socket.getOutputStream());
            Scanner scanner = new Scanner(System.in);
            Scanner serverScanner = new Scanner(reader);
            while (scanner.hasNextLine()){
                //客户端给服务端发消息
                String msg = scanner.next();
                writer.println(msg);

                //在这里被坑到了，如果使用BufferedWriter 不加newline()和flush()的话，
                //服务端BufferedReader 的readline()方法就读取不到msg,会一直阻塞下去。
                //如果使用打印流PrintStream的话，就能避免上面遇到的麻烦了
                // writer.newLine();
                writer.flush();

                //收到服务端的消息
                String s = serverScanner.nextLine();
                System.out.println("收到服务端的消息："+s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
